package com.alibaba.algo.apiimpl.feign;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.algo.apiimpl.user.SysOrgServiceImpl;
import com.alibaba.algo.apiimpl.user.SysPositionServiceImpl;
import com.alibaba.algo.constants.Constants;
import com.alibaba.algo.constants.OrgConstants;
import com.alibaba.algo.cooperation.common.BaseResult;
import com.alibaba.algo.cooperation.common.PagerEntity;
import com.alibaba.algo.cooperation.feign.service.OrgFeignService;
import com.alibaba.algo.cooperation.feign.vo.req.*;
import com.alibaba.algo.cooperation.feign.vo.res.*;
import com.alibaba.algo.cooperation.usercomponent.service.user.SysCurrentOrgService;
import com.alibaba.algo.cooperation.usercomponent.vo.req.user.SelectOrgPositionReqVO;
import com.alibaba.algo.cooperation.usercomponent.vo.req.user.SysCurrentOrgDTO;
import com.alibaba.algo.cooperation.usercomponent.vo.res.user.EmployeeInfo;
import com.alibaba.algo.core.base.YesOrNo;
import com.alibaba.algo.core.exception.BaseException;
import com.alibaba.algo.domain.user.*;
import com.alibaba.algo.dtos.user.SysOrgDTO;
import com.alibaba.algo.dtos.user.SysOrgTreeNodeDTO;
import com.alibaba.algo.dtos.user.SysUserDTO;
import com.alibaba.algo.entity.user.SysEmployee;
import com.alibaba.algo.entity.user.SysEmployeeOrg;
import com.alibaba.algo.entity.user.SysOrg;
import com.alibaba.algo.entity.user.SysUser;
import com.alibaba.algo.exception.BaseErrorCode;
import com.alibaba.algo.exception.SearchKeyErrorCode;
import com.alibaba.algo.util.DateUtil;
import com.alibaba.algo.util.StringUtil;
import com.alibaba.algo.utils.ConverterUtil;
import com.alibaba.algo.utils.TreeUtil;
import com.google.common.collect.Lists;
import com.xxl.sso.core.user.XxlSsoUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Fan.tianpeng
 * @date 2021/5/8 15:54
 */
@RestController
@Slf4j
public class OrgFeignServiceImpl implements OrgFeignService {

    @Autowired
    private SysEmployeeOrgDomain sysEmployeeOrgDomain;

    @Autowired
    private SysEmployeeDomain sysEmployeeDomain;

    @Autowired
    private SysOrgDomain sysOrgDomain;

    @Resource
    private SysPositionServiceImpl sysPositionService;

    @Resource
    private SysUserDomain sysUserDomain;

    @Resource
    private SysAppDomain sysAppDomain;


    @Resource
    private SysRoleDomain sysRoleDomain;
    @Resource
    private SysOrgRoleDomain sysOrgRoleDomain;

    @Resource
    private SysOrgServiceImpl sysOrgService;
    @Resource
    private SysCurrentOrgService sysCurrentOrgService;

    /**
     * 获取组织下的⽤户列表
     *
     * @param vo 组织标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<OrgEmployeeInfoResVO>> qryEmployeeListByOrgId(SelectOrgEmployeeReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getOrgId()) && ObjectUtils.isEmpty(vo.getOrgCode())) {
            log.error("OrgFeignServiceImpl qryEmployeeListByOrgId params are null.");
            return BaseResult.buildError(BaseErrorCode.ORG_ID_AND_ORG_CODE_IS_NULL.getCode(), BaseErrorCode.ORG_ID_AND_ORG_CODE_IS_NULL.getMessage());
        }
        //入参只有工号，没有id，根据工号查询id
        Long orgId = getOrgIdByCode(vo.getOrgId(), vo.getOrgCode());
        if (ObjectUtils.isEmpty(orgId)) {
            log.info("OrgFeignServiceImpl qryEmployeeListByOrgId result is null.Params are orgId:{},orgCode:{}", vo.getOrgId(), vo.getOrgCode());
            return BaseResult.buildSuccess(Collections.emptyList());
        }
        SysEmployeeOrg sysEmployeeOrgCon = new SysEmployeeOrg();
        sysEmployeeOrgCon.setOrgId(orgId);
        String sort = "isnull(order_num),order_num+0,isnull(employee_code),employee_code";
        List<SysEmployeeOrg> sysEmployeeOrgList = sysEmployeeOrgDomain.selectListByParaStrSort(sysEmployeeOrgCon, sort);

        Set<Long> employeeIdSet = new HashSet<>();
        List<SysEmployeeOrg> newSysEmployeeOrgList = new ArrayList<>();
        for (SysEmployeeOrg sysEmployeeOrg : sysEmployeeOrgList) {
            if (null == sysEmployeeOrg || null == sysEmployeeOrg.getEmployeeId()) {
                continue;
            }
            if (!employeeIdSet.contains(sysEmployeeOrg.getEmployeeId())) {
                employeeIdSet.add(sysEmployeeOrg.getEmployeeId());
                newSysEmployeeOrgList.add(sysEmployeeOrg);
            }
        }
        // 员工列表
        List<Long> employeeIdList = employeeIdSet.stream().collect(Collectors.toList());

        Map<Long, SysEmployee> employeeMap = sysEmployeeDomain.qryEmployeeMapByIdList(employeeIdList);
        List<OrgEmployeeInfoResVO> resVOList = new ArrayList<>();
        newSysEmployeeOrgList.forEach(s -> {
            OrgEmployeeInfoResVO resVO = new OrgEmployeeInfoResVO();
            resVO.setEmployeeId(s.getEmployeeId());
            SysEmployee sysEmployee = MapUtil.get(employeeMap, s.getEmployeeId(), SysEmployee.class, null);
            resVO.setEmployeeName(ObjectUtils.isEmpty(sysEmployee) ? "" : sysEmployee.getEmployeeName());
            //返回值增加employeeCode
            resVO.setEmployeeCode(ObjectUtils.isEmpty(sysEmployee) ? "" : sysEmployee.getEmployeeCode());
            if (!ObjectUtils.isEmpty(sysEmployee) && !ObjectUtils.isEmpty(sysEmployee.getEmployeeCode())) {
                SysUser sysUser = sysUserDomain.getOneByEmployeeCode(sysEmployee.getEmployeeCode());
                if (!ObjectUtils.isEmpty(sysUser)) {
                    resVO.setUserAccount(sysUser.getUserAccount());
                    resVO.setUserId(sysUser.getId());
                    resVO.setUserName(sysUser.getUserName());
                }
            }
            resVOList.add(resVO);
        });
        return BaseResult.buildSuccess(resVOList);
    }

    /**
     * 获取组织下的用户列表
     *
     * @param vo 组织标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<OrgUserInfoResVO>> qryUserListByOrgId(SelectOrgUserReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getOrgId()) && ObjectUtils.isEmpty(vo.getOrgCode())) {
            log.error("OrgFeignServiceImpl qryUserListByOrgId params are null.");
            return BaseResult.buildError(BaseErrorCode.ORG_ID_AND_ORG_CODE_IS_NULL.getCode(), BaseErrorCode.ORG_ID_AND_ORG_CODE_IS_NULL.getMessage());
        }
        //入参只有工号，没有id，根据工号查询id
        Long orgId = getOrgIdByCodeWithIsDeleted(vo.getOrgId(), vo.getOrgCode());
        if (ObjectUtils.isEmpty(orgId)) {
            log.info("OrgFeignServiceImpl qryUserListByOrgId result is null.Params are orgId:{},orgCode:{}", vo.getOrgId(), vo.getOrgCode());
            return BaseResult.buildSuccess(Collections.emptyList());
        }
        List<SysUser> sysUsers;
        if (!ObjectUtils.isEmpty(vo) && StringUtils.isNotEmpty(vo.getSearchKey())) {
            sysUsers = sysOrgDomain.selectUserListByOrgIdAndSearchKey(orgId, vo.getSearchKey(), vo.getIsDeleted());
        } else {
            sysUsers = sysOrgDomain.selectUserListByOrgId(orgId, vo.getIsDeleted());
        }
        if (CollectionUtils.isEmpty(sysUsers)) {
            return BaseResult.buildSuccess(Collections.emptyList());
        }
        List<OrgUserInfoResVO> result = new ArrayList<>(sysUsers.size());
        // 转换
        sysUsers.forEach(s -> {
            OrgUserInfoResVO resVO = new OrgUserInfoResVO();
            resVO.setUserId(s.getId());
            resVO.setUserName(s.getUserName());
            //返回值增加账号、工号及组织编码
            resVO.setUserAccount(s.getUserAccount());
            resVO.setEmployeeCode(s.getEmployeeCode());
            resVO.setOrgCode(vo.getOrgCode());
            resVO.setOrgId(orgId);
            resVO.setIsDeleted(s.getIsDeleted());
            result.add(resVO);
        });
        return BaseResult.buildSuccess(result);
    }

    /**
     * 根据组织和租户条件获取用户
     *
     * @param paramVo 组织标识
     * @return
     */
    @Override
    public BaseResult<List<OrgUserInfoResVO>> qryUserListByOrg(SelectOrgUserReqVO paramVo) {
        //检查参数合法性
        if (null == paramVo) {
            return BaseResult.buildError("参数对象不能为空");
        }
        if (StringUtils.isEmpty(paramVo.getAppCode())
                && StringUtils.isEmpty(paramVo.getOrgCode())
                && StringUtils.isEmpty(paramVo.getSearchKey())
                && StringUtils.isEmpty(paramVo.getUserName())
                && null == paramVo.getOrgId()
                && CollectionUtils.isEmpty(paramVo.getOrgIdList())) {
            return BaseResult.buildError("参数属性不能全部为空");
        }
        List<SysUserDTO> sysUserDtos = null;
        //不带租户条件
        if (StringUtil.isEmpty(paramVo.getAppCode())) {
            sysUserDtos = sysRoleDomain.getUsersByOrgDefaultAll(paramVo);
        }
        //不带组织条件
        if ((paramVo.getOrgIdList() == null || paramVo.getOrgIdList().isEmpty()) && !StringUtil.isEmpty(paramVo.getAppCode())) {
            sysUserDtos = sysRoleDomain.getUsersByAppDefaultAll(paramVo);
        }
        if ((paramVo.getOrgIdList() != null && !paramVo.getOrgIdList().isEmpty()) && !StringUtil.isEmpty(paramVo.getAppCode())) {
            List<SysUserDTO> usersByOrg = sysRoleDomain.getUsersByOrgDefaultAll(paramVo);
            List<SysUserDTO> usersByApp = sysRoleDomain.getUsersByAppDefaultAll(paramVo);
            sysUserDtos = usersByOrg.stream().filter(
                    usersByApp::contains).collect(Collectors.toList());
        }
        //组织--用户
        //租户--角色--用户
        List<OrgUserInfoResVO> orgUserInfoResVOS = ConverterUtil.getInstance().mapAsList(sysUserDtos, OrgUserInfoResVO.class);
        return BaseResult.buildSuccess(orgUserInfoResVOS);
    }

    @Override
    public BaseResult<List<OrgUserInfoResVO>> qryUserListByBaseOrg(SelectOrgUserReqVO paramVo) {
        //检查参数合法性
        if (null == paramVo) {
            return BaseResult.buildError("参数对象不能为空");
        }
        if ((null == paramVo.getOrgId() || paramVo.getOrgId() < 0L) && StringUtils.isEmpty(paramVo.getOrgCode())) {
            return BaseResult.buildError("参数属性orgId、orgCode不能同时为空");
        }
        //根据code查询id
        if ((null == paramVo.getOrgId() || paramVo.getOrgId() < 0L) && StringUtils.isNotEmpty(paramVo.getOrgCode())) {
            Long orgId = getOrgIdByCode(paramVo.getOrgId(), paramVo.getOrgCode());
            paramVo.setOrgId(orgId);
        }
        //根据组织查询子组织
        List<SysOrg> orgList = new ArrayList<>();
        if (null != paramVo.getOrgId()) {
            orgList = sysOrgDomain.qryChildListByOrgId(String.valueOf(paramVo.getOrgId()));
        }
        List<String> orgIds = new ArrayList<>();
        if (ObjectUtils.isEmpty(orgList)) {
            orgIds.add(String.valueOf(paramVo.getOrgId()));
        } else {
            orgIds = orgList.stream().map(s -> String.valueOf(s.getId())).collect(Collectors.toList());
        }
        paramVo.setOrgIdList(orgIds);
        paramVo.setOrgId(null);
        paramVo.setOrgCode(null);
        List<SysUserDTO> sysUserDtos = sysRoleDomain.getUsersByOrgDefaultAll(paramVo);
        List<OrgUserInfoResVO> orgUserInfoResVOS = ConverterUtil.getInstance().mapAsList(sysUserDtos, OrgUserInfoResVO.class);
        return BaseResult.buildSuccess(orgUserInfoResVOS);
    }

    /**
     * 分页获取某组织及其子孙组织下的用户列表
     *
     * @param selectOrgUserReqVO
     * @return
     */
    @Override
    public BaseResult<List<OrgUserInfoResVO>> qryUserListPageByBaseOrg(@RequestBody SelectOrgUserReqVO selectOrgUserReqVO) {
        if (null == selectOrgUserReqVO) {
            return BaseResult.buildError("参数对象不能为空");
        }
        if (selectOrgUserReqVO.getPageIndex() == null || selectOrgUserReqVO.getPageSize() == null
                || selectOrgUserReqVO.getPageIndex() <= 0 || selectOrgUserReqVO.getPageSize() <= 0) {
            return BaseResult.buildError("分页参数不合法");
        }

        return qryUserListByBaseOrg(selectOrgUserReqVO);
    }

    /**
     * 根据组织uuid获取组织下的用户列表
     *
     * @param vo 组织uuid标识
     * @return 用户列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<OrgUserInfoResVO>> qryUserListByOrgUuId(SelectOrgUserUuidReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getUuid())) {
            throw new BaseException(BaseErrorCode.PARENT_ORG_UUID_IS_NULL.getCode(), BaseErrorCode.PARENT_ORG_UUID_IS_NULL.getMessage());
        }
        SysOrg sysOrg = new SysOrg();
        sysOrg.setUuid(vo.getUuid());
        List<SysOrg> sysOrgList = sysOrgDomain.listByPara(sysOrg, null);
        if (CollectionUtils.isEmpty(sysOrgList)) {
            return BaseResult.buildSuccess(Collections.emptyList());
        }
        SysOrg org = sysOrgList.get(0);
        Long orgId = org.getId();
        String orgName = org.getOrgName();
        SelectOrgUserReqVO orgUserReqVO = new SelectOrgUserReqVO();
        orgUserReqVO.setOrgId(orgId);
        orgUserReqVO.setOrgCode(org.getOrgCode());
        BaseResult<List<OrgUserInfoResVO>> listBaseResult = this.qryUserListByOrgId(orgUserReqVO);
        listBaseResult.getData().forEach(s -> {
            s.setORG_NAME(orgName);
        });
        return listBaseResult;
    }

    /**
     * 获取当前组织下的子组织列表
     *
     * @param reqVO 父级组织标识
     * @return 组织列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<OrgInfoResVO>> qryOrgListByParentOrgId(SelectParentOrgReqVO reqVO) {
        if (ObjectUtils.isEmpty(reqVO.getParentOrgId()) && ObjectUtils.isEmpty(reqVO.getParentOrgCode())) {
            log.error("OrgFeignServiceImpl qryOrgListByParentOrgId params are null.");
            return BaseResult.buildError(BaseErrorCode.PARENT_ORG_ID_AND_PARENT_ORG_CODE_IS_NULL.getCode(), BaseErrorCode.PARENT_ORG_ID_AND_PARENT_ORG_CODE_IS_NULL.getMessage());
        }

        // 将组织Code统一转换为ID
        Long orgId = getOrgIdByCode(reqVO.getParentOrgId(), reqVO.getParentOrgCode());
        if (ObjectUtils.isEmpty(orgId)) {
            log.info("OrgFeignServiceImpl qryOrgListByParentOrgId result is null.Params are orgId:{},orgCode:{}", reqVO.getParentOrgId(), reqVO.getParentOrgCode());
            return BaseResult.buildSuccess("组织不存在", Collections.emptyList());
        }

        // 查找下层组织清单
        SelectParentOrgReqVO qrySelectParentOrgReqVO = new SelectParentOrgReqVO();
        qrySelectParentOrgReqVO.setParentOrgId(orgId);
        if (CollectionUtils.isEmpty(reqVO.getDepartmentClassificationList())) {
            reqVO.setDepartmentClassificationList(new ArrayList<>());
        }
        if (StringUtils.isNotEmpty(reqVO.getDepartmentClassification())) {
            reqVO.getDepartmentClassificationList().add(reqVO.getDepartmentClassification());
        }
        qrySelectParentOrgReqVO.setDepartmentClassificationList(reqVO.getDepartmentClassificationList());
        List<SysOrg> sysOrgList = sysOrgDomain.qryOrgListByParentIdAndDepartment(qrySelectParentOrgReqVO);
        if (CollectionUtils.isEmpty(sysOrgList)) {
            log.info("下层组织为空");
            return BaseResult.buildSuccess("下层组织为空", Collections.emptyList());
        }

        // 组装返回
        List<OrgInfoResVO> resVOList = new ArrayList<>();
        sysOrgList.forEach(item -> {
            OrgInfoResVO resVO = new OrgInfoResVO();
            resVO.setOrgId(item.getId());
            resVO.setOrgName(item.getOrgName());
            resVO.setUuid(item.getUuid());
            resVO.setParentId(item.getParentId());
            qrySelectParentOrgReqVO.setParentOrgId(item.getId());
            List<SysOrg> childOrgList = sysOrgDomain.qryOrgListByParentIdAndDepartment(qrySelectParentOrgReqVO);
            boolean isLeaf = CollectionUtils.isEmpty(childOrgList);
            if (isLeaf && StringUtils.isNotEmpty(reqVO.getCheckHasEmployee())
                    && "Y".equalsIgnoreCase(reqVO.getCheckHasEmployee())) {
                SysEmployeeOrg sysEmployeeOrgCon = new SysEmployeeOrg();
                sysEmployeeOrgCon.setOrgId(item.getId());
                List<SysEmployeeOrg> sysEmployeeOrgList = sysEmployeeOrgDomain.listByPara(sysEmployeeOrgCon, new LinkedHashMap<>());
                isLeaf = CollectionUtils.isEmpty(sysEmployeeOrgList);
            }
            resVO.setHasChild(!isLeaf);
            resVO.setIsLeaf(isLeaf);

            //返回值增加组织编码
            resVO.setOrgCode(item.getOrgCode());
            resVOList.add(resVO);
        });
        return BaseResult.buildSuccess(resVOList);
    }

    /**
     * 根据父级组织uuid获取当前组织下的子组织列表
     *
     * @param vo 父级组织uuid
     * @return 组织列表
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<List<OrgInfoResVO>> qryOrgListByParentOrgUuid(SelectParentOrgUuidReqVO vo) {
        if (ObjectUtils.isEmpty(vo.getParentOrgUuid())) {
            throw new BaseException(BaseErrorCode.PARENT_ORG_UUID_IS_NULL.getCode(), BaseErrorCode.PARENT_ORG_UUID_IS_NULL.getMessage());
        }
        SysOrg uuidOrg = new SysOrg();
        uuidOrg.setUuid(vo.getParentOrgUuid());
        List<SysOrg> uuidList = sysOrgDomain.listByPara(uuidOrg, null);
        if (CollectionUtils.isEmpty(uuidList)) {
            return BaseResult.buildSuccess(Collections.emptyList());
        }
        Long parentId = uuidList.get(0).getId();
        SelectParentOrgReqVO orgReqVO = new SelectParentOrgReqVO();
        orgReqVO.setParentOrgId(parentId);
        return this.qryOrgListByParentOrgId(orgReqVO);
    }

    /**
     * 通过组织id列表查询对应的组织名映射关系
     *
     * @param vo 组织id列表
     * @return 组织映射关系
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<Map<Long, String>> qryOrgNameMap(List<Long> vo) {
        if (CollectionUtils.isEmpty(vo)) {
            return BaseResult.buildSuccess(Collections.emptyMap());
        }
        Map<Long, SysOrg> sysOrgMap = sysOrgDomain.qryOrgMapWithIsDeletedByIdList(vo);
        Map<Long, String> collect = sysOrgMap.entrySet().stream()
                .filter(map -> StringUtils.isNotEmpty(map.getValue().getOrgName()))
                .collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().getOrgName(), (v1, v2) -> v2));
        return BaseResult.buildSuccess(collect);
    }

    /**
     * 根据组织code集合查询组织code和组织id的对应关系map集合
     *
     * @param vo 组织标识列表
     * @return 组织映射关系
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public BaseResult<Map<String, Long>> qryOrgIdMapByOrgCodes(List<String> vo) {
        if (CollectionUtils.isEmpty(vo)) {
            return BaseResult.buildSuccess(Collections.emptyMap());
        }
        if (vo.size() > Constants.BATCH_QUERY_COUNT) {
            return BaseResult.buildError("批量查询不能超过" + Constants.BATCH_QUERY_COUNT + "条");
        }
        Map<String, SysOrg> sysOrgMap = sysOrgDomain.qryOrgMapByCodeList(vo);
        Map<String, Long> collect = sysOrgMap.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().getId(), (v1, v2) -> v2));
        return BaseResult.buildSuccess(collect);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)
    public List<FeignGetFirstLevelOrgResponseVO> getFirstLevelOrgList() {
        return getFirstLevelOrgListByParam(null);
    }

    @Override
    public List<FeignGetFirstLevelOrgResponseVO> getFirstLevelOrgListByParam(GetFirstLevelOrgReqVo vo) {
        SysOrg sysOrg = new SysOrg();
        //sysOrg.setParentId(Constants.ROOT_ORG_ID);
        sysOrg.setParentId(OrgConstants.ROOT_ORG_ID);
        if (null != vo) {
            if (StringUtils.isNotEmpty(vo.getDataSource())) {
                sysOrg.setDataSource(vo.getDataSource());
            }
            if (StringUtils.isNotEmpty(vo.getBusinessLevel())) {
                sysOrg.setBusinessLevel(vo.getBusinessLevel());
            }
            if (StringUtils.isNotEmpty(vo.getDepartmentClassification())) {
                sysOrg.setDepartmentClassification(vo.getDepartmentClassification());
            }
        }
        LinkedHashMap<String, Object> sortMap = new LinkedHashMap<String, Object>();
        sortMap.put("gmtCreated", "DESC");
        List<SysOrg> sysOrgList = sysOrgDomain.listByPara(sysOrg, sortMap);
        if (CollectionUtils.isEmpty(sysOrgList)) {
            return Collections.emptyList();
        }
        List<FeignGetFirstLevelOrgResponseVO> resList = new ArrayList<>();
        for (SysOrg org : sysOrgList) {
            FeignGetFirstLevelOrgResponseVO getFirstLevelOrgResponseVO = new FeignGetFirstLevelOrgResponseVO();
            BeanUtils.copyProperties(org, getFirstLevelOrgResponseVO);
            // 查询当前组织的岗位数量
            SelectOrgPositionReqVO selectOrgPositionReqVO = new SelectOrgPositionReqVO();
            selectOrgPositionReqVO.setOrgId(org.getId());
            int positionNum = (int) sysPositionService.getPositionNumByOrgId(selectOrgPositionReqVO).getData();
            getFirstLevelOrgResponseVO.setPositionNum(Integer.valueOf(positionNum).longValue());
            // 时间转换
            getFirstLevelOrgResponseVO.setExpireStartTime(DateUtil.format(org.getExpireStartTime()));
            if (!ObjectUtils.isEmpty(org.getExpireEndTime())) {
                getFirstLevelOrgResponseVO.setExpireEndTime(DateUtil.format(org.getExpireEndTime()));
            }
            // 校验是否含有下级组织
            if (!ObjectUtils.isEmpty(sysOrgDomain.qryOrgListByParentId(org.getId(), sortMap))) {
                getFirstLevelOrgResponseVO.setHasChild(true);
            }
            resList.add(getFirstLevelOrgResponseVO);
        }
        return resList;
    }

    @Override
    public BaseResult<List<UserInfoResVO>> qryUserListByOrgAndRole(List<SysOrgRoleReqVO> sysOrgRoleReqVOList) {
        // 校验参数
        sysOrgRoleReqVOList = filterSysOrgRoleReqVOList(sysOrgRoleReqVOList);
        if (CollectionUtils.isEmpty(sysOrgRoleReqVOList)) {
            log.info("OrgFeignServiceImpl qryUserListByOrgAndRole result is null.Params are sysOrgRoleReqVOList:{}", sysOrgRoleReqVOList);
            return BaseResult.buildSuccess(Collections.emptyList());
        }
        List<UserInfoResVO> userInfoResVOList = new ArrayList<>();
        sysOrgRoleReqVOList.forEach(
                vo -> {
                    // 查询组织下的用户
                    SelectOrgUserReqVO selectOrgUserReqVO = new SelectOrgUserReqVO();
                    selectOrgUserReqVO.setOrgId(vo.getOrgId());
                    selectOrgUserReqVO.setOrgCode(vo.getOrgCode());
                    List<SysUserDTO> sysUserDTOList = sysRoleDomain.getUsersByOrg(selectOrgUserReqVO);
                    List<UserInfoResVO> userInfoResVOByOrg = ConverterUtil.getInstance().mapAsList(sysUserDTOList, UserInfoResVO.class);
                    // 查询角色下的用户
                    GetRoleUserReqVO getRoleUserReqVO = new GetRoleUserReqVO();
                    getRoleUserReqVO.setRoleId(vo.getRoleId());
                    getRoleUserReqVO.setRoleCode(vo.getRoleCode());
                    List<UserInfoResVO> userInfoResVOByRole = sysRoleDomain.getUsersByRole(getRoleUserReqVO);
                    // 组织和角色下用户求交集
                    if (!CollectionUtils.isEmpty(userInfoResVOByOrg) && !CollectionUtils.isEmpty(userInfoResVOByRole)) {
                        List<UserInfoResVO> userInfoResVOS = userInfoResVOByOrg.stream().filter(
                                userInfoResVOByRole::contains).collect(Collectors.toList());
                        userInfoResVOList.addAll(userInfoResVOS);
                    }
                }
        );
        return BaseResult.buildSuccess(userInfoResVOList);
    }

    @Override
    public BaseResult<List<UserInfoResVO>> qryUserListByOrgAndRoleExtend(List<SysOrgRoleReqVO> sysOrgRoleReqVOList) {
        if (CollectionUtils.isEmpty(sysOrgRoleReqVOList)) {
            log.info("OrgFeignServiceImpl qryUserListByOrgAndRoleExtend result is null.Params are sysOrgRoleReqVOList:{}", sysOrgRoleReqVOList);
            return BaseResult.buildSuccess(Collections.emptyList());
        }
        List<UserInfoResVO> userInfoResVOList = new ArrayList<>();
        sysOrgRoleReqVOList.forEach(
                vo -> {
                    // 查询组织下的用户
                    List<UserInfoResVO> userInfoResVOByOrg = null;
                    Long orgId = vo.getOrgId();
                    String orgCode = vo.getOrgCode();
                    if (!ObjectUtils.isEmpty(orgId) || !ObjectUtils.isEmpty(orgCode)) {
                        SelectOrgUserReqVO selectOrgUserReqVO = new SelectOrgUserReqVO();
                        selectOrgUserReqVO.setOrgId(orgId);
                        selectOrgUserReqVO.setOrgCode(orgCode);
                        List<SysUserDTO> sysUserDTOList = sysRoleDomain.getUsersByOrg(selectOrgUserReqVO);
                        userInfoResVOByOrg = ConverterUtil.getInstance().mapAsList(sysUserDTOList, UserInfoResVO.class);
                    }
                    // 查询角色下的用户
                    List<UserInfoResVO> userInfoResVOByRole = null;
                    Long roleId = vo.getRoleId();
                    String roleCode = vo.getRoleCode();
                    if (!ObjectUtils.isEmpty(roleId) || !ObjectUtils.isEmpty(roleCode)) {
                        GetRoleUserReqVO getRoleUserReqVO = new GetRoleUserReqVO();
                        getRoleUserReqVO.setRoleId(roleId);
                        getRoleUserReqVO.setRoleCode(roleCode);
                        userInfoResVOByRole = sysRoleDomain.getUsersByRole(getRoleUserReqVO);
                    }
                    // 1.组织和角色都传且有用户，两者用户求交集
                    if (!CollectionUtils.isEmpty(userInfoResVOByOrg) && !CollectionUtils.isEmpty(userInfoResVOByRole)) {
                        List<UserInfoResVO> finalUserInfoResVOByRole = userInfoResVOByRole;
                        List<UserInfoResVO> userInfoResVOS = userInfoResVOByOrg.stream().filter(
                                finalUserInfoResVOByRole::contains).collect(Collectors.toList());
                        userInfoResVOList.addAll(userInfoResVOS);
                    } else if (!CollectionUtils.isEmpty(userInfoResVOByOrg)) {
                        // 2.只有组织下有用户
                        userInfoResVOList.addAll(userInfoResVOByOrg);
                    } else if (!CollectionUtils.isEmpty(userInfoResVOByRole)) {
                        // 3.只有角色下有用户
                        userInfoResVOList.addAll(userInfoResVOByRole);
                    }
                }
        );
        return BaseResult.buildSuccess(userInfoResVOList);
    }

    /**
     * 根据组织编码或者组织id查组织详细信息
     *
     * @param vo
     * @return
     */
    @Override
    public BaseResult<FeignOrgDetailResponse> getOrgDetail(GetOrgDetailReqVo vo) {
        if (vo.empty()) {
            return BaseResult.buildError(-1, "入参不合法，orgId,orgCode至少传一个。");
        }
        if (StringUtil.isNotEmpty(vo.getOrgCode()) && vo.getOrgCode().length() > 128) {
            return BaseResult.buildError(-1, "orgCode不允许超过128。");
        }
        SysOrg orgParam = new SysOrg();
        orgParam.setId(vo.getOrgId());
        orgParam.setOrgCode(vo.getOrgCode());
        if (StringUtil.isNotEmpty(vo.getIsDeleted())) {
            orgParam.setIsDeleted(vo.getIsDeleted());
        }
        List<SysOrg> sysOrgs = sysOrgDomain.listByParaWithIsDeleted(orgParam);
        if (ObjectUtils.isEmpty(sysOrgs)) {
            return BaseResult.buildSuccess();
        }
        SysOrg org = sysOrgs.get(0);
        FeignOrgDetailResponse orgResp = ConverterUtil.getInstance().map(org, FeignOrgDetailResponse.class);
        return BaseResult.buildSuccess(orgResp);
    }

    private List<SysOrgRoleReqVO> filterSysOrgRoleReqVOList(List<SysOrgRoleReqVO> sysOrgRoleReqVOList) {
        sysOrgRoleReqVOList = sysOrgRoleReqVOList.stream().filter(
                vo -> {
                    if (ObjectUtils.isEmpty(vo.getOrgId()) && StringUtils.isBlank(vo.getOrgCode())) {
                        log.warn(BaseErrorCode.ORG_ID_ORG_CODE_IS_NULL.getMessage() + "Params are vo:{}", vo);
                        return false;
                    }
                    if (ObjectUtils.isEmpty(vo.getRoleId()) && StringUtils.isBlank(vo.getRoleCode())) {
                        log.warn(BaseErrorCode.ROLE_ID_ROLE_CODE_IS_NULL.getMessage() + "Params are vo:{}", vo);
                        return false;
                    }
                    return true;
                }
        ).collect(Collectors.toList());
        return sysOrgRoleReqVOList;
    }

    /**
     * 入参只有工号，没有id，根据工号查询id
     */
    private Long getOrgIdByCode(Long id, String code) {
        Long orgId = null;
        if ((ObjectUtils.isEmpty(id) || id <= 0) && !ObjectUtils.isEmpty(code)) {
            SysOrg org = sysOrgDomain.selectByOrgCode(code);
            if (!ObjectUtils.isEmpty(org) && !ObjectUtils.isEmpty(org.getId())) {
                orgId = org.getId();
            }
        } else {
            orgId = id;
        }
        return orgId;
    }

    private Long getOrgIdByCodeWithIsDeleted(Long id, String code) {
        Long orgId = null;
        if ((ObjectUtils.isEmpty(id) || id <= 0) && !ObjectUtils.isEmpty(code)) {
            SysOrg org = sysOrgDomain.selectByOrgCodeWithIsDeleted(code);
            if (!ObjectUtils.isEmpty(org) && !ObjectUtils.isEmpty(org.getId())) {
                orgId = org.getId();
            }
        } else {
            orgId = id;
        }
        return orgId;
    }

    @Override
    public BaseResult selectOrgTreeByCondition(@RequestBody SelectOrgUserEmployeeVO vo) {
        //根据条件模糊查询组织列表
        List<SysOrgDTO> orgList;
        if (null == vo || null == vo.getFlag() || (vo.getFlag() != 1 && vo.getFlag() != 2)) {
            throw new BaseException(SearchKeyErrorCode.FLAG_ILLEGAL.getCode(), SearchKeyErrorCode.FLAG_ILLEGAL.getMessage());
        }
        if (vo.getFlag() == 1) {//根据组织条件查询
            orgList = sysOrgDomain.selectOrgByOrgCondition(vo);
        } else {
            //根据人员条件查询
            if (null != vo.getEmployeePreciseFlag() && vo.getEmployeePreciseFlag() == 1) {//工号精确匹配
                orgList = sysOrgDomain.selectOrgByEmployeePreciseCondition(vo);
            } else {
                //模糊查询
                orgList = sysOrgDomain.selectOrgByEmployeeCondition(vo);
            }
        }
        //组织节点集合
        Set<SysOrgTreeNodeDTO> nodeList = new HashSet<>();
        if (!ObjectUtils.isEmpty(orgList)) {
            for (SysOrgDTO sysOrgDTO : orgList) {
                //根据组织id查询父级到根节点信息(包含节点本身)
                List<SysOrg> orgParentList = sysOrgDomain.selectOrgIdListRecursiveToRoot(sysOrgDTO.getId());
                if (!ObjectUtils.isEmpty(orgParentList)) {
                    for (SysOrg sysOrg : orgParentList) {
                        SysOrgTreeNodeDTO sysOrgTreeNodeDTO = new SysOrgTreeNodeDTO();
                        BeanUtils.copyProperties(sysOrg, sysOrgTreeNodeDTO);
                        nodeList.add(sysOrgTreeNodeDTO);
                    }
                }
            }
        }
        if (!ObjectUtils.isEmpty(nodeList) && vo.getFlag() == 2) {
            if (!CollectionUtils.isEmpty(vo.getOrgIdList())) {
                List<Long> userOrgTree = nodeList.stream().map(SysOrgTreeNodeDTO::getId).collect(Collectors.toList());
                boolean isJoin = userOrgTree.stream().anyMatch(vo.getOrgIdList()::contains);
                if (!isJoin) {
                    nodeList = new HashSet<>();
                }
            }
            //查询条件中无组织信息要把人员信息返回
            for (SysOrgTreeNodeDTO sysOrgTreeNodeDTO : nodeList) {
                //每个树节点查询模糊匹配的人员信息
                if (ObjectUtils.isEmpty(vo.getSearchKey())) {//查询条件无人员条件只返回组织下人员数量
                    vo.setOrgId(sysOrgTreeNodeDTO.getId());
                    Integer notMatchCount = sysUserDomain.countUserEmployeeListByCondition(vo);
                    sysOrgTreeNodeDTO.setUserCount(notMatchCount);
                } else {//模糊匹配到的用户员工信息
                    vo.setOrgId(sysOrgTreeNodeDTO.getId());
                    List<EmployeeInfo> sysUserList = sysUserDomain.selectUserEmployeeListByCondition(vo);
                    sysOrgTreeNodeDTO.setUserList(new HashSet<>(sysUserList));
                    sysOrgTreeNodeDTO.setUserCount(sysUserList.size());
                }
            }
        }
        //所有节点构造树型结构
        Set<SysOrgTreeNodeDTO> nodeSet = TreeUtil.buildTree(nodeList);
        return BaseResult.buildSuccess(nodeSet);
    }

    /**
     * 分页查询组织信息
     *
     * @param vo 查询条件对象，包含同后管页面的条件
     * @return
     */
    @Override
    public BaseResult selectPage(SelectOrgListRequestVO vo) {
        com.alibaba.algo.cooperation.usercomponent.vo.req.user.SelectOrgListRequestVO qryVO =
                new com.alibaba.algo.cooperation.usercomponent.vo.req.user.SelectOrgListRequestVO();
        BeanUtils.copyProperties(vo, qryVO);
        PagerEntity pagerEntity = sysOrgService.selectPage(qryVO);
        return BaseResult.buildSuccess(pagerEntity);
    }

    private int compareOrg(Integer intDeptType1, Integer intDeptType2, Integer sort1, Integer sort2) {
        if (null != intDeptType1 && null != intDeptType2 && null != sort1 && null != sort2) {
            if (intDeptType1.intValue() != intDeptType2.intValue()) {
                return intDeptType1 - intDeptType2;
            }
            return sort1 - sort2;
        }
        if (null != intDeptType1 && null != intDeptType2) {
            return intDeptType1 - intDeptType2;
        }
        if (null != intDeptType1 && null == intDeptType2) {
            return -1;
        }
        if (null == intDeptType1 && null != intDeptType2) {
            return 1;
        }
        if (null != sort1 && null != sort2) {
            return sort1 - sort2;
        }
        if (null != sort1 && null == sort2) {
            return -1;
        }
        if (null == sort1 && null != sort2) {
            return 1;
        }
        return 0;
    }

    /**
     * 组织列表排序
     */
    private void sortOrgVOList(List<SysOrgVO> childVoList) {
        if (CollectionUtils.isEmpty(childVoList)) {
            return;
        }
        childVoList.sort(new Comparator<SysOrgVO>() {
            @Override
            public int compare(SysOrgVO o1, SysOrgVO o2) {
                if (null == o1 || null == o2) {
                    return 0;
                }
                String strDeptType1 = o1.getDepartmentClassification();
                String strDeptType2 = o2.getDepartmentClassification();
                Integer intDeptType1 = null;
                Integer intDeptType2 = null;
                if (StringUtils.isNotEmpty(strDeptType1)) {
                    intDeptType1 = Integer.valueOf(strDeptType1);
                }
                if (StringUtils.isNotEmpty(strDeptType2)) {
                    intDeptType2 = Integer.valueOf(strDeptType2);
                }
                Integer sort1 = o1.getSort();
                Integer sort2 = o2.getSort();
                return compareOrg(intDeptType1, intDeptType2, sort1, sort2);
            }
        });
    }

    /**
     * 根据组织id组织编码查询组织及其所有孩子节点
     *
     * @param vo
     * @return
     */
    @Override
    public BaseResult selectOrgAndChildListByCondition(SelectOrgListRequestVO vo) {
        if (null == vo || (null == vo.getId() && StringUtils.isEmpty(vo.getOrgCode()))) {
            throw new BaseException(BaseErrorCode.ORG_ID_ORG_CODE_IS_NULL.getCode(), BaseErrorCode.ORG_ID_ORG_CODE_IS_NULL.getMessage());
        }
        SysOrg param = new SysOrg();
        BeanUtils.copyProperties(vo, param);
        SysOrg sysOrg = sysOrgDomain.selectOneByCondition(param);
        OrgAndChildListVO orgAndChildListVo = new OrgAndChildListVO();
        if (!ObjectUtils.isEmpty(sysOrg)) {
            BeanUtils.copyProperties(sysOrg, orgAndChildListVo);
            List<SysOrg> childList = sysOrgDomain.qryChildListByOrgId(String.valueOf(orgAndChildListVo.getId()));
            childList.removeIf(item -> orgAndChildListVo.getId().equals(item.getId()));
            List<SysOrgVO> childVoList = new ArrayList<>();
            childList.stream().forEach(item -> {
                SysOrgVO sysOrgVO = new SysOrgVO();
                BeanUtils.copyProperties(item, sysOrgVO);
                childVoList.add(sysOrgVO);
            });
            sortOrgVOList(childVoList);
            orgAndChildListVo.setChildList(childVoList);
            return BaseResult.buildSuccess(orgAndChildListVo);
        } else {
            return BaseResult.buildSuccess(null);
        }
    }

    @Override
    public BaseResult<Boolean> insertOrUpdateCurrentOrg(AddOrUpdateCurrentOrgVO vo) {
        // 校验登录用户信息
        XxlSsoUser xxlSsoUser = sysUserDomain.checkLoginUserInfo(vo);
        SysCurrentOrgDTO sysCurrentOrgDTO = new SysCurrentOrgDTO();
        sysCurrentOrgDTO.setUserId(Long.valueOf(xxlSsoUser.getUserid()));
        sysCurrentOrgDTO.setUserName(xxlSsoUser.getUsername());
        sysCurrentOrgDTO.setOrgId(vo.getOrgId());
        sysCurrentOrgDTO.setOrgCode(vo.getOrgCode());
        sysCurrentOrgDTO.setOrgName(vo.getOrgName());
        sysCurrentOrgService.insertOrUpdate(sysCurrentOrgDTO);
        return BaseResult.buildSuccess(true);
    }

    @Override
    public BaseResult<List<OrgInfoResVO>> selectOrgListByOrgNameAndParentCode(SelectOrgByNameParentReqVO paramVO) {
        // 检查参数合法性
        String rtnMessage = null;
        if (null == paramVO) {
            rtnMessage = "参数对象不能为空";
            log.warn(rtnMessage);
            return BaseResult.buildError(rtnMessage);
        }
        if (StringUtils.isEmpty(paramVO.getOrgName()) || StringUtils.isEmpty(paramVO.getParentOrgCode())) {
            rtnMessage = "组织名称和父组织编码都不能为空";
            log.warn(rtnMessage);
            return BaseResult.buildError(rtnMessage);
        }

        // 执行查询
        SysOrg parentOrg = sysOrgDomain.selectByOrgCodeWithIsDeleted(paramVO.getParentOrgCode());
        if (null == parentOrg) {
            rtnMessage = String.format("未找到父组织,编码:%s", paramVO.getParentOrgCode());
            log.warn(rtnMessage);
            return BaseResult.buildError(rtnMessage);
        }
        List<SysOrg> childOrgList = sysOrgDomain.qryChildListByOrgId(String.valueOf(parentOrg.getId()));
        if (null == childOrgList || childOrgList.size() <= 0) {
            rtnMessage = String.format("编码为:[%s]的父组织下无子组织", paramVO.getParentOrgCode());
            log.warn(rtnMessage);
            return BaseResult.buildError(rtnMessage);
        }
        List<OrgInfoResVO> orgInfoResVOList = new ArrayList<>();
        String orgName = paramVO.getOrgName().trim();
        for (SysOrg childOrg : childOrgList) {
            if (null == childOrg || StringUtils.isEmpty(childOrg.getOrgName())
                    || YesOrNo.Y.name().equals(childOrg.getIsDeleted())) { //过滤掉已删除的
                continue;
            }
            if (orgName.equals(childOrg.getOrgName())) {
                OrgInfoResVO orgInfoResVO = new OrgInfoResVO();
                orgInfoResVO.setOrgId(childOrg.getId());
                orgInfoResVO.setOrgCode(childOrg.getOrgCode());
                orgInfoResVO.setOrgName(childOrg.getOrgName());
                orgInfoResVO.setUuid(childOrg.getUuid());
                orgInfoResVOList.add(orgInfoResVO);
            }
        }
        if (null == orgInfoResVOList || orgInfoResVOList.size() <= 0) {
            rtnMessage = String.format("编码为:[%s]的父组织下,无名称为[%s]的子组织", paramVO.getParentOrgCode(), orgName);
            log.warn(rtnMessage);
            return BaseResult.buildError(rtnMessage);
        }
        return BaseResult.buildSuccess(orgInfoResVOList);
    }

    @Override
    public BaseResult<List<OrgInfoVO>> selectParentOrgByCurrentOrgId(@RequestParam Long orgId) {
        if (null == orgId) {
            return BaseResult.buildError("入参为空");
        }
        List<SysOrg> orgList = sysOrgDomain.selectOrgIdListRecursiveToRoot(orgId);
        List<OrgInfoVO> returnOrgInfo = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(orgList)) {
            orgList.forEach(item -> {
                OrgInfoVO orgInfo = new OrgInfoVO();
                orgInfo.setOrgId(item.getId());
                orgInfo.setOrgName(item.getOrgName());
                orgInfo.setOrgCode(item.getOrgCode());
                orgInfo.setParentOgId(item.getParentId());
                orgInfo.setUuid(item.getUuid());
                returnOrgInfo.add(orgInfo);
            });
        }
        return BaseResult.buildSuccess(returnOrgInfo);
    }
}
